package com.walkline.util.ui;

import net.rim.device.api.system.AccelerometerChannelConfig;
import net.rim.device.api.system.AccelerometerData;
import net.rim.device.api.system.AccelerometerListener;
import net.rim.device.api.system.AccelerometerSensor;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.AccelerometerSensor.Channel;

public class MyShakeListener implements AccelerometerListener
{
	private static final int SPEED_SHRESHOLD = 1001;
	private static final int UPTATE_INTERVAL_TIME = 700;

	private OnShakeListener onShakeListener;
	private Channel channel;

	private short lastX;
	private short lastY;
	private short lastZ;
	private long lastUpdateTime;

	public MyShakeListener() {start();}

	public void start()
	{
		AccelerometerChannelConfig config = new AccelerometerChannelConfig(AccelerometerChannelConfig.TYPE_RAW, true, false, 50);
		channel = AccelerometerSensor.openChannel(Application.getApplication(), config);
		channel.setAccelerometerListener(this);
	}

	public void stop()
	{
		channel.close();
		channel.removeAccelerometerListener();
	}

	public void setOnShakeListener(OnShakeListener listener) {onShakeListener = listener;}

	public interface OnShakeListener {public void onShake();}

	public void onData(AccelerometerData accData)
	{
		long currentUpdateTime = System.currentTimeMillis();
		long timeInterval = currentUpdateTime - lastUpdateTime;

		if (timeInterval > UPTATE_INTERVAL_TIME)
		{
			lastUpdateTime = currentUpdateTime;

			short x = accData.getLastXAcceleration();
			short y = accData.getLastYAcceleration();
			short z = accData.getLastZAcceleration();

System.out.println(getClass().getName() + ": x=" + x + ", y=" + y + ", z=" + z);
System.out.println(getClass().getName() + ": lastX=" + lastX + ", lastY=" + lastY + ", lastZ=" + lastZ);

			float deltaX = x - lastX;
			float deltaY = y - lastY;
			float deltaZ = z - lastZ;

System.out.println(getClass().getName() + ": deltaX=" + deltaX + ", deltaY=" + deltaY + ", deltaZ=" + deltaZ);

			//double speed = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) / timeInterval * 10000;
			double speedX = Math.abs(deltaX);
			double speedY = Math.abs(deltaY);

			lastX = x;
			lastY = y;
			lastZ = z;

			if (speedX >= SPEED_SHRESHOLD || speedY >= SPEED_SHRESHOLD)
			{
				System.out.println(getClass().getName() + ": speedX=" + +speedX + ", speedY=" + speedY + ", Shaked!!!");

				lastX = 0;
				lastY = 0;
				lastZ = 0;

				onShakeListener.onShake();
			}
		}
	}
}